﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace 第十次作业
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        async Task<string> AccessTheWebAsync(string url)
        {
            HttpClient client = new HttpClient();
            Task<string> task = client.GetStringAsync(url); //异步
            label3.Text = "异步请求中.............";
            DoIndependentWork(); //做其他事
            string urlContents = await task; //等待异步执行完毕
            label3.Text = "异步请求完成！！！";
            return urlContents;
        }

        async private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
            try
            {
                //https://www.baidu.com/s?wd=
                //https://cn.bing.com/search?q=

                string url = "https://cn.bing.com/search?q=" + textBox1.Text;
                string content = await AccessTheWebAsync(url);
                //textBox2.Text += content;

                MatchCollection mc3 = Regex.Matches(content, @"[\u4e00-\u9fa5]+"); //满足pattern的匹配集合
                foreach (Match match in mc3)
                {
                    if (textBox2.Text.Length <= 200)
                    {
                        textBox2.Text += match;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show("错误1");
            }
        }
        private void DoIndependentWork()
        {
            textBox3.Text = "";
            try
            {
                string url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&ch=8&tn=1&wd=" + textBox1.Text;
                WebClient client = new WebClient();
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0");
                byte[] pageData = client.DownloadData(url);
                string pageHtml = Encoding.Default.GetString(pageData);
                //textBox3.Text += pageHtml;

                MatchCollection mc2 = Regex.Matches(pageHtml, @"[\u4e00-\u9fa5]+"); //满足pattern的匹配集合
                foreach (Match match in mc2)
                {
                    if (textBox3.Text.Length <= 1000)
                    {
                        textBox3.Text += match;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show("错误2");
            }
        }
    }
}
